package Sever端;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerThread extends Thread {
    private final Socket socket;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader br = null;
        PrintWriter pw = null;
        try {
            //服务器输入
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String info;
            StringBuilder result = new StringBuilder();
            while ((info = br.readLine()) != null) {
                result.append(SeverDeal.dealCmd(info));//处理指令
            }
            socket.shutdownInput();
            //服务器输出
            pw = new PrintWriter(socket.getOutputStream());
            System.out.println("|" + result + "|");
            pw.write(result + " ");//输出服务器处理后的回应
            pw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            try {
                if (pw != null)
                    pw.close();
                if (br != null)
                    br.close();
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}